import React, { Component } from 'react';
import CustomBreadcrumb from '../../components/CustomBreadcrumb';
import EditUserForm from './components/EditUserForm';
import { Loading } from '../commons'
import { hashHistory } from 'react-router';
import { UserService, ChannelService } from '../../services'

export default class AddUser extends Component {
  static displayName = 'AddUser';

  constructor(props) {
    super(props);
    this.state = {
      loading : true,
      channel : [],
      value : {
        ...this.props.location.state,
        username : this.props.params.username,
      }
    };
  }

  componentDidMount = async() =>{
    let fullUser = await UserService.fullInfo(this.props.params.username);
    let channel = await ChannelService.getChannelWithEnable()
    this.setState({ 
      channel: channel.map(c=>{return { label : c.name, value : c.id}}) , 
      loading : false, 
      value : {
        ...fullUser.user,
        channel : fullUser.channel
      }
    })
  }

  onSubmit = async(data) =>{
    await UserService.update(data)
    hashHistory.push('/user/list')
    return true
  }

  render() {
    const breadcrumb = [
      { text: '用户管理', link: '#/user/list' },
      { text: '修改用户', link: null },
    ];
    return (
      <div className="adduser-page">
        <Loading loading={this.state.loading}/>
        <CustomBreadcrumb dataSource={breadcrumb} />
        { this.state.loading ? null : <EditUserForm channel={this.state.channel} value={this.state.value} onSubmit={this.onSubmit}/>  }
      </div>
    );
  }
}
